import PermissionsDefinition from '@/permissionsDefinition';

/**
 * 权限配置结构类
 */
type AccessParams = {
  code: string;
  path: string;
  authority?: string[];
  children?: AccessParams[];
}

/**
 * @see https://umijs.org/zh-CN/plugins/plugin-access
 * */
export default function access(initialState: { currentUser?: API.UserSession | undefined }) {
  const { currentUser } = initialState || {};
  return {
    /**
     * 根据权限代码表判断是否具有使用权限
     * 超级管理员(策略:SuperAdmin)将拥有全部权限
     * @param route 当前路由
     * @returns boolean
     */
    checkingModuleEntry: (route: Partial<AccessParams>) => {
      const { authority, code } = route;
      const permissionCodes = [...authority ?? [], code!];
      return permissionCodes.some(p => currentUser?.permissions?.includes(p))
        || currentUser?.permissions?.includes(PermissionsDefinition.SuperAdmin);
    },
    /**
     * 检查模块集合的权限
     */
    checkingModules: (route: Partial<AccessParams>) => {
      return route.children?.map(m => m.code).some(p => currentUser?.permissions?.includes(p))
        || currentUser?.permissions?.includes(PermissionsDefinition.SuperAdmin)
    },
    /**
     * 检测操作项
     * 超级管理员(策略:SuperAdmin)将拥有全部权限
     * @param code 操作函数
     * @returns boolean
     */
    canOperatorItem: (code: () => void) => {
      if (currentUser?.permissions) {
        return currentUser.permissions.includes(PermissionsDefinition.SuperAdmin)
          || currentUser.permissions.includes(code.name);
      }
      return false;
    }
  };
}